/**
 * Copyright (C) 2018 - 2020 https://github.com/LeeYan9
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.task;

import com.bifrost.cbentity.SapProduct;
import com.bifrost.cbrepository.SapProductRepository;
import com.bifrost.entity.Product;
import com.bifrost.entity.SapGoods;
import com.bifrost.model.ProductAddModel;
import com.bifrost.repository.ProductRepository;
import com.bifrost.repository.SapGoodsRepository;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Lee
 * Create Class on 2018/9/21
 * @com.bifrost.task
 * @wechat-mall
 */
@Component
@JobHandler("syncExternalCategory")
public class SyncExternalCategory extends IJobHandler{

    @Autowired
    public SapGoodsRepository goodsRepository;
    @Autowired
    public ProductRepository productRepository;
    @Autowired
    private SapProductRepository sapProductRepository;

    public void updateExternalCategory(List<Product> products) {
        for (Product product : products) {
            try {
                String externalId = product.getExternalId();
                SapGoods goods = goodsRepository.findFirstByMatnr(externalId);
                SapProduct sapProduct=null;
                if(goods==null){
                    sapProduct = sapProductRepository.findFirstByMatnr(externalId);
                }
                productRepository.updateCategoryCode(product.getProductId(),goods==null?sapProduct.getMatkl():goods.getMatkl());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        List<Product> products = productRepository.findAllByExternalCcategoryLike("A%");
        if(products.isEmpty()){
            return ReturnT.SUCCESS;
        }
        XxlJobLogger.log("同步商品分类编码开始");
        updateExternalCategory(products);
        XxlJobLogger.log("同步商品分类编码完成");
        return ReturnT.SUCCESS;
    }
}
